package com.csproj.basic.repository.impl;

import com.csproj.basic.domain.CollarRecord;
import com.csproj.basic.repository.custom.CollarRecordRepositoryCustom;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;

public class CollarRecordRepositoryImpl implements CollarRecordRepositoryCustom {
    @PersistenceContext
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    /**
     * 机构分页查询方法
     *
     * @param map      参数
     * @param pageable 分页对象
     * @return
     */
    public Page<CollarRecord> findPageList(Map<String, Object> map, Pageable pageable) {
        //拼hql
        String hql = " from CollarRecord wh where wh.deletedFlag = 0 ";

        Map<String, Object> queryParams = new HashMap<>();

        //查询
        Page<CollarRecord> fieldList = query(hql, pageable, queryParams);
        //返回
        return fieldList;
    }


    /**
     * 根据设备ID查询，分页方法
     *
     * @param map
     * @param pageable
     * @return
     */
    @Override
    public Page<CollarRecord> findPageListByDeviceId(Map<String, Object> map, Pageable pageable) {
        Map<String, Object> queryparams = new HashMap<>();

        String deviceId = (String) map.get("deviceId");
        String name = (String) map.get("name");
        ZonedDateTime startTime = (ZonedDateTime) map.get("startTime");
        ZonedDateTime endTime = (ZonedDateTime) map.get("endTime");


        String hql = " select cr from CollarRecord cr left join UserInfo ui on ui.id = cr.receiverId where cr.deletedFlag = 0 ";
        if (StringUtils.isNotBlank(deviceId)) {
            hql += " and cr.deviceId = :deviceId";
            queryparams.put("deviceId", deviceId);
        }

        if (StringUtils.isNotBlank(name)) {
            hql += " and ui.account like :name ";
            queryparams.put("name", "%" + name + "%");
        }

        //ZonedDateTime startDate = DateUtils.changeStringToZonedDateTime(startTime, "yyyy-MM-dd HH:mm:ss");
        if (startTime != null) {
            queryparams.put("startDate", startTime);
            hql += " and  ( cr.receiveDate >= :startDate or cr.backDate >= :startDate )";

        }

        //ZonedDateTime endDate = DateUtils.changeStringToZonedDateTime(endTime, "yyyy-MM-dd HH:mm:ss");
        if (endTime != null) {
            queryparams.put("endDate", endTime);
            hql += " and  ( cr.receiveDate < :endDate or cr.backDate < :endDate )";

        }

        Page<CollarRecord> fieldList = query(hql, pageable, queryparams);


        return fieldList;
    }
}

